<template>
  <el-form :model="form" label-width="120px">
    <el-form-item label="角色名称">
      <el-input v-model="form.roleName" />
    </el-form-item>
    <el-form-item label="角色代号">
      <el-input v-model="form.roleCode" />
    </el-form-item>
    <el-form-item label="角色权限">
      <el-tree ref="treeRef" :data="menus" :props="treeProps" show-checkbox />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">新增角色</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { rolePost } from "../../api/user";
import { routes } from "../../router";
export default {
  data() {
    return {
      menus: routes[0].children, //存放侧边菜单数据包
      form: {
        roleName: "",
        roleCode: "",
      },
      treeProps: {
        // label: "path",
        label: (data, node) => {
          //指定树形组件的渲染标题
          // console.log(data, node);
          return data.meta.label;
        },
      },
    };
  },
  methods: {
    onSubmit() {
      let roleMenu = this.getCheckedTree();
      rolePost({ ...this.form, roleMenu }).then((res) => {
        console.log(res);
      });
    },
    getCheckedTree() {
      // console.log(this.$refs);
      const list = this.$refs.treeRef.getCheckedNodes(true); //参数为tree，则只获取被勾选的子节点，父节点后续通过逻辑代码算出来
      // console.log(list);
      let tempList = []; //临时记录已经匹配过的父级path
      let result = []; //存放最终处理结果
      list.forEach((item) => {
        const parent = this.menus.find((mitem) => {
          return mitem.children?.some(
            //注意处理mitem没有children的情况
            (child) => child.meta.label == item.meta.label
          );
        });
        //有父级
        if (parent) {
          if (!tempList.includes(parent.path)) {
            //如果某个父级从未被匹配过
            tempList.push(parent.path);
            result.push({
              path: parent.path,
              meta: parent.meta,
              children: [item], //此处的item是长子
            });
          } else {
            result.find((ele) => ele.path == parent.path).children.push(item); //此处的item是次子
          }
        } else {
          //无父级
          result.push(item);
        }
      });
      // console.log(result);
      return result;
    },
  },
};
</script>
